/*
 * Copyright (C) 2012 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package com.example.google.tv.picasanotifier;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.google.tv.picasanotifier.model.AlbumEntry;
import com.example.google.tv.picasanotifier.model.AlbumFeed;
import com.example.google.tv.picasanotifier.model.PhotoData;
import com.example.google.tv.picasanotifier.model.PhotoEntry;
import com.example.google.tv.picasanotifier.model.PicasaUrl;
import com.example.google.tv.picasanotifier.model.UserFeed;
import com.google.api.client.http.HttpTransport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Activity that displays photos along with its title.
 */
public class PhotoActivity extends Activity implements OnItemClickListener {

    private static final String TAG = "PhotoActivity";

    private GridView mGridView;

    private ArrayList<PhotoData> mPhotos;

    private String mAlbumName, mUserName;

    private PhotoData mData;

    private ArrayList<PhotoData> mPhotoData = new ArrayList<PhotoData>();

    private ArrayList<PhotoEntry> mPhotoEntries = new ArrayList<PhotoEntry>();;

    private ImageView mImageView;
    
    private ImageManager mImageManager;

    final Picasa picasa = Picasa.get();

    private HttpTransport transport = picasa.picasaInit();

    List<PhotoEntry> mPhotosEntry;

    AlbumEntry mAlbum;

    PhotoEntry pEntry;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_view);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            mAlbumName = extras.getString("albumname");
            mUserName = extras.getString("username");
        }
        mPhotos = getPhotos(mAlbumName);
        mGridView = (GridView)findViewById(R.id.picasa_photo);
        mGridView.setAdapter(new PhotoAdapter(this));
        mGridView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
        Intent intent = new Intent(PhotoActivity.this, SlideShowActivity.class);
        intent.putExtra("pos", pos);
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("photos", mPhotoData);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * Retrieve the list of photos for the selected album.
     * 
     * @param albumname The album name to retrieve the photos from.
     * @return List of photos of the specified album
     */
    public ArrayList<PhotoData> getPhotos(String albumname) {

        List<AlbumEntry> albums = picasa.getUserAlbums(mUserName);
        try {
            PicasaUrl url = PicasaUrl.fromRelativePath(Picasa.API_FEED_URL + mUserName);

            // page through results
            while (true) {
                UserFeed userFeed = UserFeed.executeGet(transport, url);
                if (userFeed.mAlbums != null) {
                    albums.addAll(userFeed.mAlbums);
                }
                for (AlbumEntry album : userFeed.mAlbums)
                    if (album.title.equals(albumname)) {
                        mPhotos = getPhotobyAlbum(transport, album);
                    }
                String nextLink = userFeed.getNextLink();
                if (nextLink == null) {
                    break;
                }
            }

        } catch (IOException e) {
            Log.e(TAG,"Couldn't obtain the content",e);
            albums.clear();
        }
        return mPhotos;
    }

    /**
     * Get the photo information of each photo
     * 
     * @param transport Set up the HTTP transport to build the url
     * @param album The list of albums of a selected user.
     * @return The list of photo information associated with the photo
     */
    private ArrayList<PhotoData> getPhotobyAlbum(HttpTransport transport, AlbumEntry album) {
        mPhotoEntries = new ArrayList<PhotoEntry>();
        if (album.numPhotos != 0) {
            PicasaUrl url = new PicasaUrl(album.getFeedLink());
            url.imgmax = 1280;
            AlbumFeed feed;
            try {
                feed = AlbumFeed.executeGet(transport, url);
                for (PhotoEntry photo : feed.photos) {
                    mPhotoEntries.addAll(feed.photos);
                    mData = new PhotoData();
                    mData.setPhotoTitle(photo.title);
                    mData.setPhotoUrl(photo.mediaGroup.thumbnail.url);
                    mData.setPhotoFullUrl(photo.mediaGroup.content.url);
                    mData.setContentType(photo.mediaGroup.content.type);
                    mPhotoData.add(mData);
                }
            } catch (IOException e) {
                Log.e(TAG, "Could not obtain the content");
            }
        }
        return mPhotoData;
    }

    /**
     * Adapter to display photos of the given album in a Gridview.
     */
    public class PhotoAdapter extends BaseAdapter {
        public PhotoAdapter(Context context) {
            mImageManager = new ImageManager(context);
        }

        @Override
        public int getCount() {
            return mPhotoData.size();
        }

        @Override
        public Object getItem(int position) {
            return mPhotoData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null) {
                LayoutInflater li = getLayoutInflater();
                view = li.inflate(R.layout.image_photo, null);
            } else {
                view = convertView;
            }

            TextView tv = (TextView)view.findViewById(R.id.photo_text);
            tv.setText(mPhotoData.get(position).getPhotoTitle());
            mImageView = (ImageView)view.findViewById(R.id.photo);
            mImageManager
                    .showImage(mPhotoEntries.get(position).mediaGroup.thumbnail.url, mImageView);
            return view;
        }
    }
}
